package cn.yunyichina.provider.message.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.yunyichina.provider.iface.entity.common.Response;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import cn.yunyichina.provider.framework.exception.CallException;
import cn.yunyichina.provider.framework.mvc.dao.BaseDao;
import cn.yunyichina.provider.framework.page.PageInfo;
import cn.yunyichina.provider.iface.entity.ErrorCodeDefine;
import cn.yunyichina.provider.message.dao.MessageHistoryDao;
import cn.yunyichina.provider.message.entity.MessageHistory;
import cn.yunyichina.utils.convert.JsonUtils;

/**
 * app消息中心
 * Created by Administrator on 2016/9/13.
 */
@Service("messagehistoryServiceImpl")
public class MessageHistoryServiceImpl {
    
	private static final Logger logger = LoggerFactory.getLogger(MessageHistoryServiceImpl.class);
    @Autowired
    private MessageHistoryDao messageHistoryDao;

    /**
     * app消息列表
     * yyt.message.messagehistory.list
     * @param strJson
     * @return
     */
    public Response listMessageHistory(String strJson) {
//		return listEntity(strJson,MessageHistory.class,messageHistoryDao);

		Response response = new Response();
		Map<String, Object> result = new HashMap<>();
		MessageHistory query = JsonUtils.parseObject(strJson, MessageHistory.class);
//		if(StringUtils.isBlank(query.getUserId())){
//			response.setResultCodeAndMessage("8001","user_id不能为空");
//			return response;
//		}
		List<MessageHistory> list = null;
		List<String> orderColumns = new ArrayList<String>();
		PageInfo pageInfo = null;
		if(query != null){
			orderColumns.add("CREATED_TIME DESC");
			pageInfo = JsonUtils.parseObject(strJson, PageInfo.class);
			list  = messageHistoryDao.select(query, orderColumns , false ,pageInfo);
		}

		if(list != null && list.size() > 0){
			if(pageInfo != null && pageInfo.getPageNum() !=null && pageInfo.getPageSize() != null){
				long totalSize = messageHistoryDao.selectCount(query);
				pageInfo.setTotal(totalSize);
//				pageInfo.setPages((pageInfo.getTotal().intValue() + pageInfo.getPageSize() - 1) / pageInfo.getPageSize());
				result.put("pageNum",pageInfo.getPageNum());
				result.put("pageSize",pageInfo.getPageSize());
				result.put("total",pageInfo.getTotal());

			}
			result.put("list", list);
			response.setResult(JsonUtils.toJsonString(result));
			response.setResultCodeAndMessage("0", "查询成功!");
		}else{
			response.setResultCodeAndMessage("0" , "查无结果");
		}
		return response;
    }


    /**
	 * 标记已读
	 * yyt.message.messagehistory.mark
	 * @param
	 */
    public void markMessageHistory(String strJson) {
    	JSONObject param = JsonUtils.parseObject(strJson);
    	messageHistoryDao.markIsRead(param.getString("id"));
    }
    
    /**
	 * 新增
	 * yyt.message.messagehistory.add
	 * @param strJson MessageHistory对象全部信息
	 */
    public void addMessageHistory(String strJson) {
    	MessageHistory messageHistory = JsonUtils.parseObject(strJson,MessageHistory.class);
    	messageHistoryDao.insert(messageHistory);
    }
	
	/**
	 * 通用解析-组装类型的列表查询
	 * @param strJson
	 * @param clz
	 * @param dao
	 * @return
	 */
	private <T> List<T> listEntity(String strJson,Class<T> clz,BaseDao<T> dao) {
		try {
			logger.debug("listEntity入参:" + strJson);
			JSONObject jsonObj = JsonUtils.parseObject(strJson);
			T entity = JsonUtils.parseObject(strJson, clz);

			PageInfo pageInfo = null;
			if (jsonObj.containsKey("pageInfo")) {
				pageInfo = JsonUtils.parseObject(jsonObj.getJSONObject("page_info"), PageInfo.class);
			} else {
				pageInfo = new PageInfo();
			}
			List<String> orderColumns = null;
			if (jsonObj.containsKey("orderColumns") && StringUtils.isNotEmpty(jsonObj.getString("orderColumns"))) {
				orderColumns = new ArrayList<String>();
				String str = jsonObj.getString("orderColumns");
				if (str.startsWith("[")) {
					str = str.substring(1);
				}
				if (str.endsWith("]")) {
					str = str.substring(0,str.length() - 1);
				}
				String[] listObj = str.split(",");
				for (Object field : listObj) {
					orderColumns.add((String) field);
				}
			}

			List<String> selects = null;
			if (jsonObj.containsKey("selects") && StringUtils.isNotEmpty(jsonObj.getString("selects"))) {
				selects = new ArrayList<String>();
				String str = jsonObj.getString("selects");
				if (str.startsWith("[")) {
					str = str.substring(1);
				}
				if (str.endsWith("]")) {
					str = str.substring(0,str.length() - 1);
				}
				String[] listObj = str.split(",");
				for (Object field : listObj) {
					selects.add((String) field);
				}
			}

			boolean isAsc = true;
			if (jsonObj.containsKey("isAsc")) {
				isAsc = jsonObj.getBooleanValue("isAsc");
			}

			List<T> list = dao.select(entity, selects, orderColumns, isAsc, pageInfo);

			logger.debug("listEntity：" + JsonUtils.toJsonString(list));

			return list;
		} 
		catch (CallException ce) {
			throw ce;
		}
		catch (Exception e) {
			logger.error("查询错误");
			logger.error(ErrorCodeDefine.getStackTrace(e));
			throw new CallException(ErrorCodeDefine.MESSAGE_PARAM, "查询异常",e);
		}

	}

	/**
	 * 获取未读消息数量
	 * yyt.message.messagehistory.unread.get
	 * @param strJson
	 * @return
	 */
	public Response getMessageHistoryUnread(String strJson) {
//		return listEntity(strJson,MessageHistory.class,messageHistoryDao);

		Response response = new Response();
		Map<String, Long> result = new HashMap<>();
		MessageHistory query = JsonUtils.parseObject(strJson, MessageHistory.class);
		if(StringUtils.isBlank(query.getUserId())){
			response.setResultCodeAndMessage("8001","user_id不能为空");
			return response;
		}
		query.setIsRead((short) 1);
		long count = messageHistoryDao.selectCount(query);
		result.put("count",count);
		response.setResult(JsonUtils.toJsonString(result));
		response.setResultCodeAndMessage("0", "查询成功!");

		return response;
	}
}
